import { BrowserHistory } from 'history'
import * as React from 'react'
import { MicroAppContext } from '../context/MicroAppContext'
import { getMatchItem } from '../utils/getMatchItem'
import { debug } from '../utils/log'
/**
 * 匹配大布局
 * @param param0 
 * @returns 
 */
const useMatcher = ({ rules }: any) => {
  const { history } = React.useContext(MicroAppContext)
  const [element, setElement] = React.useState(null)
  const prevRef = React.useRef(null)
  // React.useEffect(() => {
  //   matchElement()

  // }, [children])
  const matchElement = () => {
    const a = getMatchItem(rules, window.location.pathname);
    if (prevRef.current == a.path) {
      return
    }
    prevRef.current = a.path
    debug('匹配到', a)
    if (a) {

      setElement(a.element)
    }
  }
  React.useEffect(() => {

    matchElement()
  }, [rules])
  React.useEffect(() => {
    const unlisten = (history as BrowserHistory).listen(() => {
      matchElement()
    })
    return () => {
      unlisten()
    }
  }, [])

  return {
    element
  }
}
export default useMatcher


